from app import create_app, db
from app.models.user import User
from app.models.product import Product
from app.models.order import Order
from app.models.order_item import OrderItem
from werkzeug.security import generate_password_hash

def init_db():
    app = create_app()
    with app.app_context():
        # 创建所有表
        db.create_all()
        
        # 添加测试用户
        admin = User(
            username='admin',
            email='admin@example.com',
            password=generate_password_hash('admin123'),
            role='admin'
        )
        user = User(
            username='user',
            email='user@example.com',
            password=generate_password_hash('user123'),
            role='user'
        )
        db.session.add(admin)
        db.session.add(user)
        
        # 添加测试商品
        products = [
            Product(
                name='iPhone 13',
                description='Apple iPhone 13 128GB',
                price=5999.00,
                stock=100,
                category='手机',
                image_url='https://example.com/iphone13.jpg'
            ),
            Product(
                name='MacBook Pro',
                description='Apple MacBook Pro 14-inch',
                price=12999.00,
                stock=50,
                category='电脑',
                image_url='https://example.com/macbook.jpg'
            ),
            Product(
                name='AirPods Pro',
                description='Apple AirPods Pro',
                price=1999.00,
                stock=200,
                category='耳机',
                image_url='https://example.com/airpods.jpg'
            )
        ]
        for product in products:
            db.session.add(product)
        
        # 添加测试订单
        order = Order(
            user_id=2,  # user的ID
            total_amount=7998.00,
            status='completed',
            shipping_address='北京市朝阳区xxx街道',
            payment_method='支付宝'
        )
        db.session.add(order)
        
        # 添加订单项
        order_items = [
            OrderItem(
                order_id=1,
                product_id=1,  # iPhone 13
                quantity=1,
                price=5999.00
            ),
            OrderItem(
                order_id=1,
                product_id=3,  # AirPods Pro
                quantity=1,
                price=1999.00
            )
        ]
        for item in order_items:
            db.session.add(item)
        
        # 提交所有更改
        db.session.commit()
        print('数据库初始化完成！')

if __name__ == '__main__':
    init_db() 